<?php

namespace pay\modules\frontend\models;

use common\libs\Tools;
use Yii;

/**
 * This is the model class for table "pay_order_info".
 *
 * @property int $oid
 * @property int $app_id app_id
 * @property int $aid 应用id
 * @property in 商户id
 * @property string $pay_order_sn 支付订单号
 * @property string $mar_order_sn 商户订单号
 * @property string|null $ref_order_sn 退款单号
 * @property int $pay_money 支付金额
 * @property string $pay_status 1-订单生成，2-支付中，3-支付成功，4-处理完成，5-已退款
 * @property string $is_refund 1-未退款，2-已退款
 * @property string|null $client_id 客户端ip
 * @property string|null $facility 设备
 * @property int $refund_money 退款金额
 * @property string|null $goods_name 商品名称
 * @property string|null $goods_desc 商品备注
 * @property string|null $callback_url 回调地址
 * @property string|null $failure_time 失效时间
 * @property string|null $success_time 成功时间
 * @property string $create_time 创建时间
 */
class OrderInfo extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'pay_order_info';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['app_id', 'aid', 'pay_order_sn', 'mar_order_sn', 'pay_money', 'create_time'], 'required'],
            [['app_id', 'aid', 'pay_money', 'refund_money'], 'integer'],
            [['pay_status', 'is_refund'], 'string'],
            [['failure_time', 'success_time', 'create_time'], 'safe'],
            [['pay_order_sn', 'mar_order_sn', 'ref_order_sn'], 'string', 'max' => 24],
            [['client_id'], 'string', 'max' => 32],
            [['facility'], 'string', 'max' => 10],
            [['goods_name'], 'string', 'max' => 64],
            [['goods_desc', 'callback_url','attach'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'oid' => 'Oid',
            'app_id' => 'App ID',
            'aid' => 'Aid',
            'pay_order_sn' => 'Pay Order Sn',
            'mar_order_sn' => 'Mar Order Sn',
            'ref_order_sn' => 'Ref Order Sn',
            'pay_money' => 'Pay Money',
            'pay_status' => 'Pay Status',
            'is_refund' => 'Is Refund',
            'client_id' => 'Client ID',
            'facility' => 'Facility',
            'refund_money' => 'Refund Money',
            'goods_name' => 'Goods Name',
            'goods_desc' => 'Goods Desc',
            'callback_url' => 'Callback Url',
            'failure_time' => 'Failure Time',
            'success_time' => 'Success Time',
            'create_time' => 'Create Time',
        ];
    }

    /** 后端接口，创建订单
     * @param $params
     * @return bool
     */
    public function addOrder($params)
    {
        $data['OrderInfo']['app_id'] = $params['appId'];
        $data['OrderInfo']['aid'] = $params['aid'];
        $data['OrderInfo']['pay_order_sn'] = $params['pay_order_sn'];
        $data['OrderInfo']['mar_order_sn'] = $params['payNo'];
        $data['OrderInfo']['pay_money'] = $params['amount'];
        $data['OrderInfo']['pay_status'] = '1';
        $data['OrderInfo']['is_refund'] = '1';
        $data['OrderInfo']['client_id'] = Yii::$app->request->userIP;
        $data['OrderInfo']['goods_name'] = $params['commodityName'];
        $data['OrderInfo']['goods_desc'] = $params['goodsDesc'];
        $data['OrderInfo']['callback_url'] = $params['callBackUrl'];
        $data['OrderInfo']['failure_time'] = !empty($params['validTime'])?$params['validTime']:0;
        $data['OrderInfo']['create_time'] = date("Y-m-d H:i:s",$params['timestamp']);
        $data['OrderInfo']['attach'] = $params['attach'];

        if ($this->load($data) and $this->validate()){
            if ($this->save(0)){
                return true;
            }
        }
        return false;
    }

    /*** 前端接口，创建订单
     * @param $data
     * @return bool
     */
    public function createOrder($data)
    {
        $data['OrderInfo']['app_id'] = $data['appId'];
        $data['OrderInfo']['aid'] = $data['aid'];
        $data['OrderInfo']['pay_order_sn'] = $data['pay_order_sn'];
        $data['OrderInfo']['mar_order_sn'] = $data['payNo'];
        $data['OrderInfo']['pay_money'] = $data['amount'];
        $data['OrderInfo']['pay_status'] = '1';
        $data['OrderInfo']['is_refund'] = '1';
        $data['OrderInfo']['client_id'] = Yii::$app->request->userIP;
        $data['OrderInfo']['goods_name'] = !empty($data['commodityName'])?$data['commodityName']:'';
        $data['OrderInfo']['goods_desc'] = !empty($data['goodsDesc'])?$data['goodsDesc']:'';
        $data['OrderInfo']['callback_url'] = !empty($data['callBackUrl'])?$data['callBackUrl']:'';
        $data['OrderInfo']['failure_time'] = !empty($data['validTime'])?$data['validTime']:0;
        $data['OrderInfo']['create_time'] = date("Y-m-d H:i:s",time());
        $data['OrderInfo']['attach'] = $data['attach'];
        if ($this->load($data) and $this->validate()){
            if ($this->save(0)){
                return true;
            }
        }
        return false;
    }


    /*** 查询订单信息
     * @param $app_id    实例id
     * @param $mar_order_sn     商户订单号
     * @param int $type         查询类型  1：显示信息，2：状态信息，3：全部信息
     * @return array|bool|null|\yii\db\ActiveRecord
     */
    public function checkOrderInfo($app_id,$mar_order_sn,$type = 1)
    {
        if ($type == 1){
            $selectData = ['oid','pay_order_sn','mar_order_sn','ref_order_sn','pay_money','real_money','pay_status','is_refund','refund_money','success_time','create_time'];
        }elseif ($type == 2){
            $selectData = ['oid','pay_order_sn','mar_order_sn','real_money','pay_status','success_time','create_time'];
        }else{
            $selectData = '';
        }

        if (!empty($app_id) and !empty($mar_order_sn)){
            $orderInfo = self::find()->where('app_id = :aid and mar_order_sn = :marsn',[':aid' => $app_id,':marsn' => $mar_order_sn])->select($selectData)->asArray()->one();
            return $orderInfo;
        }
        return false;
    }


    public function checkOrderStatus($data)
    {
        $app_id = $data['appId'];
        $mar_order_sn = Tools::cutstrHtml($data['payNo']);

        if (!empty($app_id) and !empty($mar_order_sn)){
            $orderInfo = self::find()->where('app_id = :aid and mar_order_sn = :marsn',[':aid' => $app_id,':marsn' => $mar_order_sn])->select(['oid','pay_order_sn','mar_order_sn','pay_status','success_time','pay_time'])->asArray()->one();
            return $orderInfo;
        }
        return false;
    }


    public function getInfo($mar_order_sn)
    {
        $info = self::find()->where('mar_order_sn = :msn',[':msn' => $mar_order_sn])->orderBy(['oid' => SORT_DESC])->asArray()->one();
        if (empty($info)){
            return '';
        }
        return $info;
    }




    public function getCheckOrderList($app_id,$startTime,$endTime)
    {
            $searchModel = self::find()->where('app_id = :aid',[':aid' => $app_id])->andWhere(['between','pay_time',$startTime.'000',$endTime.'000']);
            $orderList = $searchModel->select(['pay_order_sn','mar_order_sn','real_money','pay_status','success_time'])->asArray()->all();
            return $orderList;





    }


}
